package com._21cn._front;

import com._21cn._front.utils.PageUtil;
import com._21cn.cms.common.ErrorCode;
import com._21cn.cms.common.obj.ResponseObj;
import com._21cn.cms.common.utils.ResponseUtil;
import com._21cn.framework.utils.StringUtil;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class GenerateServlet extends HttpServlet
{
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        String requestUrl = request.getRequestURL().toString();
        requestUrl = StringUtil.html2Text(requestUrl, "");
        String bean = PageUtil.getPageBean(requestUrl);
        ResponseObj responseObj = generate(request, bean);
        sendPcResult(response, responseObj);
    }

    private ResponseObj generate(HttpServletRequest request, String bean)
    {
        ResponseObj responseObj = new ResponseObj();
        ServletContext servletContext = request.getSession().getServletContext();
        WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        if (!StringUtil.isEmpty(bean)) {
            GenerateHandler GenerateHandler = (GenerateHandler)wac.getBean(bean);
            responseObj = GenerateHandler.generate(request);
        } else {
            responseObj.setErrorCode(ErrorCode.ERROR_GENERATOR_NOT_FOUND);
            responseObj.setMessage("没找到对应的页面生成器");
        }
        return responseObj;
    }

    public void sendPcResult(HttpServletResponse response, ResponseObj responseObj) throws IOException {
        String pageContent = "";
        int code = responseObj.getErrorCode().intValue();
        switch (code) {
            case 0:
                pageContent = responseObj.getMessage();
                ResponseUtil.returnMsg(response, pageContent);
                return;
            case 3:
                response.sendError(404);
                return;
        }

        response.sendError(404);
    }
}